#include "Timer.h"
#include "AutoLock.h"
#include <map>
#include <boost/tuple/tuple.hpp>
#include "SparseArray.h"
#include "LastError.h"

using namespace std;

namespace yet {

SparseArray<Timer*> timers;
ThreadLock timersLock;

void CALLBACK MyTimerProc(HWND hwnd, UINT uMsg, UINT_PTR idEvent, DWORD dwTime) {
	AutoLock tl(timersLock);
	Timer* timer = timers.get(idEvent, 0);
	tl.unLock();
	if(timer){
		if(timer->OnTimer){
			timer->OnTimer(timer);
		}
	}
}

Timer::Timer() {
	timerID = 0;
}
Timer::~Timer() {
	stop();
}
bool Timer::start(UINT milliSeconds) {
	assert(milliSeconds);
	stop();
	AutoLock lock(idLock);
	timerID = SetTimer(0, 0, milliSeconds, &MyTimerProc);
	if(timerID){
		AutoLock tl(timersLock);
		timers.put(timerID, this);
	}else{
		LastError e;
		e.print();
	}
	return timerID != 0;
}
void Timer::stop() {
	if (isActive()) {
		AutoLock lock(idLock);
		KillTimer(0, timerID);
		AutoLock tl(timersLock);
		timers.remove(timerID);
		timerID = 0;
	}
}
bool Timer::isActive() {
	AutoLock lock(idLock);
	return timerID != 0;
}
}
